package top.zspaces.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.zspaces.order.bean.Order;
import top.zspaces.order.properties.OrderProperties;
import top.zspaces.order.service.OrderService;

import java.text.MessageFormat;

//@RefreshScope // 自动刷新功能，获取nacos配置发布。
@Slf4j
@RestController
//@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    OrderProperties orderProperties;

    @GetMapping("/config")
    public String config() {
        return String.format("""
                        OrderController信息： <br/>
                        order.timeout=%s; <br/>
                        order.auto-confirm=%s; <br/>
                        order.db-url=%s; <br/>
                        """,
                orderProperties.getTimeout(),
                orderProperties.getAutoConfirm(),
                orderProperties.getDbUrl());
    }

    @GetMapping("/create")
    public Order createOrder(@RequestParam("userId") Long userId, @RequestParam("productId") Long productId) {
        return orderService.createOrder(productId, userId);
    }

    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order", fallback = "seckillFallback")
    public Order seckill(@RequestParam(value = "userId", required = false ) Long userId, @RequestParam(value = "productId",defaultValue = "1000") Long productId) {
        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }

    public Order seckillFallback(@RequestParam("userId") Long userId, @RequestParam("productId") Long productId, Throwable exception) {
        System.out.println(MessageFormat.format("seckill兜底回调：<productId>{0}<userId>{1}", productId, userId));
        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setAddress("异常信息：" + exception.getClass());
        return order;
    }

    @GetMapping("/writeDb")
    public String writeDb() {
        log.info("writeDb...");
        return "writeDb success...";
    }

    @GetMapping("/readDb")
    public String readDb() {
        log.info("readDb...");
        return "readDb success...";
    }

}
